//
//  BaseNetwork.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/8/16.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "BaseNetwork.h"

// 默认超时时间
#define NETWORK_TIMEOUT_DEFAULT             10

// 核心服务超时时间
#define NETWORK_TIMEOUT_LONG                20

// 启动广告时间
#define NETWORK_TIMEOUT_AD                  2

@interface BaseNetwork ()

@property (nonatomic, strong) NSString *currentUrlString;

@property (nonatomic, assign) NSTimeInterval netTimeoutInterval;//超时时间
@property (nonatomic, assign) NSTimeInterval startTimeSeconds;//请求开始时间

@property (nonatomic, assign) NSInteger retryCount;// 失败重试，第一次失败后重试两次

@end

@implementation BaseNetwork

//初始化设置
- (instancetype)init
{
    if(self = [super init])
    {
        self.enableCache = YES;// 默认开启缓存
        self.netTimeoutInterval = NETWORK_TIMEOUT_DEFAULT;
        self.needRetry = YES;
        
    }
    return self;
}

//设置接口类型---重写set方法
- (void)setInterfaceType:(InterfaceType)interfaceType
{
    _interfaceType = interfaceType;
    switch (_interfaceType) {
        case InterfaceTypeDefault:
        {
            self.netTimeoutInterval = NETWORK_TIMEOUT_DEFAULT;
        }
            break;
        case InterfaceTypeLong:
        {
            self.netTimeoutInterval = NETWORK_TIMEOUT_LONG;
        }
            break;
        case InterfaceTypeAD:
        {
            self.netTimeoutInterval = NETWORK_TIMEOUT_AD;
        }
            break;
            
        default:
            break;
    }
}

//懒加载
- (AFHTTPSessionManager *)httpSessionManager
{
    if(!_httpSessionManager)
    {
        _httpSessionManager = [AFHTTPSessionManager manager];
        
        //request
        // 分别设置请求以及相应的序列化器
        _httpSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [_httpSessionManager.requestSerializer setValue:[NSString stringWithFormat:@"Anxin/Na/iphone/%@/{%@}", iOSVer,APP_VERSION] forHTTPHeaderField:@"User-Agent:Native"];
        /**设置请求超时时间*/
        _httpSessionManager.requestSerializer.timeoutInterval = self.netTimeoutInterval;
        
        /**设置相应的缓存策略*/
        _httpSessionManager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        
        /**复杂的参数类型 需要使用json传值-设置请求内容的类型*/
        // GET请求用 application/json
        [_httpSessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
        /**设置apikey ------类似于自己应用中的tokken---此处仅仅作为测试使用*/
        //    [_httpSessionManager.requestSerializer setValue:apikey forHTTPHeaderField:@"apikey"];
        
        // response
        AFJSONResponseSerializer * response = [AFJSONResponseSerializer serializer];
        
        response.removesKeysWithNullValues = YES;
        
        _httpSessionManager.responseSerializer = response;
        
        /**设置接受的类型*/
        [_httpSessionManager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"application/json",@"text/json",@"text/javascript",@"text/html", nil]];
        
    }
    return _httpSessionManager;
}

- (void)sendGetRequestURL:(NSString *)urlString parameters:(NSDictionary *)parameters completionBlockWithSuccess:(CompletionBlock)completionBlock andFailure:(FailureBlock)failure
{
    if(urlString == nil || [urlString isEqualToString:@""])
    {
        return;
    }
    self.currentUrlString = [[self handleUrlStr:urlString withDict:parameters] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"get请求 url %@",self.currentUrlString);
    self.startTimeSeconds = [[NSDate new] timeIntervalSince1970];//请求时间
    [self.httpSessionManager GET:self.currentUrlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *resultDictionary = nil;
        NSString *errorMsg = @"出错了";
        BOOL isSuccess = NO;
        if([responseObject isKindOfClass:[NSDictionary class]])
        {
            resultDictionary = (NSDictionary *)responseObject;
            NSString *code = [NSString stringWithFormat:@"%@", [resultDictionary objectForKey:@"code"]];
            
            if ([code isEqualToString:@"0"]) {
                
                isSuccess = YES;
                
            } else {
                
                if (!ISEMPTYSTRING(resultDictionary[@"message"])) {
                    errorMsg = STRING(resultDictionary[@"message"]);
                }
            }
            // 判断特殊code
//            [GlobalTool handleInterfaceErrorCode:code];
        }
        
        if(isSuccess){
            completionBlock(resultDictionary);
        }
        else{
            failure(nil, errorMsg);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -1001) {
            failure(error,TimeoutErrorToastText);
        } else {
            failure(error, @"出错了");
        }
    }];
}

- (void)sendPostRequestURL:(NSString *)urlString parameters:(NSDictionary *)parameters completionBlockWithSuccess:(CompletionBlock)completionBlock andFailure:(FailureBlock)failure
{
    if (urlString == nil || [urlString isEqualToString:@""]) {
        return;
    }
    
    NSMutableDictionary *postValues = [self handleParams:parameters];
    NSLog(@"%@\n%@",urlString,postValues);
    
    
    // POST请求用 application/x-www-form-urlencoded 或者置为nil，AF自动处理
    [self.httpSessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    //    [self.httpSessionManager.requestSerializer setValue:nil forHTTPHeaderField:@"Content-Type"];
    
    self.startTimeSeconds = [[NSDate new] timeIntervalSince1970];// 请求开始时间
    [self.httpSessionManager POST:urlString parameters:postValues progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //        progress(1.0*uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSDictionary *resultDictionary = nil;
        NSString *errorMsg = @"出错了";
        BOOL isSuccess = NO;
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            
            resultDictionary = (NSDictionary *)responseObject;
            // 判断
            NSString *code = [NSString stringWithFormat:@"%@",[resultDictionary objectForKey:@"code"]];
            if ([code isEqualToString:@"0"]) {
                
                isSuccess = YES;
                
            } else {
                if (!ISEMPTYSTRING(resultDictionary[@"message"])) {
                    errorMsg = STRING(resultDictionary[@"message"]);
                }
            }
            
            //             判断特殊code
//            [GlobalTool handleInterfaceErrorCode:code];
            
        }
        
        if (isSuccess) {
            // 成功
            completionBlock(resultDictionary);
        } else {
            // 失败
            failure(nil,errorMsg);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error.code == -1001) {
            failure(error,TimeoutErrorToastText);
        } else {
            failure(error,@"出错了");
        }
        
        // 去掉重试功能
        //        if (self.needRetry) {
        //
        //            self.retryCount++;
        //            if (self.retryCount <= 2) {
        //                NSLog(@"第 %zd 次重试",self.retryCount);
        //                [self sendPostRequestURL:urlString parameters:postValues completionBlockWithSuccess:completionBlock andFailure:failure];
        //            } else {
        //                failure(error);
        //            }
        //            
        //        } else {
        //            
        //            failure(error);
        //        }
    }];
}

- (void)uploadImageRequestURL:(NSString *)urlString imageArray:(NSArray *)imageArray parameters:(NSDictionary *)parameters progress:(ProgressBlock)progress completionBlockWithSuccess:(CompletionBlock)completionBlock andFailure:(FailureBlock)failure
{
    self.httpSessionManager.requestSerializer.timeoutInterval = 120;
    [self.httpSessionManager.requestSerializer setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
    NSMutableDictionary *postValues = [self handleParams:parameters];
    
    self.currentUrlString = [[self handleUrlStr:urlString withDict:parameters] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"self.currentUrlString = %@",self.currentUrlString);

    [self.httpSessionManager POST:self.currentUrlString parameters:postValues constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSUInteger i = 0;
        for (UIImage *image in imageArray) {
            NSData *data = UIImageJPEGRepresentation(image, 0.5);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
            
            /*
             此方法参数
             1. 要上传的[二进制数据]
             2. 对应网站上[upload.php中]处理文件的[字段"file"]
             3. 要保存在服务器上的[文件名]
             4. 上传文件的[mimeType]
             */
            
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
            i++;
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(1.0*uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *resultDictionary = nil;
        NSString *errorMsg = @"出错了";
        BOOL isSuccess = NO;
        NSLog(@"responseObject =%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            
            resultDictionary = (NSDictionary *)responseObject;
            // 判断
            NSString *code = [NSString stringWithFormat:@"%@",[resultDictionary objectForKey:@"code"]];
            if ([code isEqualToString:@"0"]) {
                
                isSuccess = YES;
                
            } else {
                
                if (!ISEMPTYSTRING(resultDictionary[@"message"])) {
                    errorMsg = STRING(resultDictionary[@"message"]);
                }
            }
            
            // 判断特殊code
//            [GlobalTool handleInterfaceErrorCode:code];
            
        }
        
        if (isSuccess) {
            // 成功
            completionBlock(resultDictionary);
        } else {
            // 失败
            failure(nil,errorMsg);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -1001) {
            failure(error,TimeoutErrorToastText);
        } else {
            failure(error,@"出错了");
        }
    }];
}


#pragma mark - local method---get拼接参数
- (NSString *)handleUrlStr:(NSString *)urlString withDict:(NSDictionary *)dict{
    
    NSString *resultString = @"";
    NSString *markStr = @"";
    
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //转为字符型
    if ([urlString rangeOfString:@"?"].location == NSNotFound) {
        markStr = @"?";
    } else {
        markStr = @"&";
    }
    NSString *sign = @"MhxZkhl:Xhkj-Anxin@201705";
    if(dict)//对参数进行排序
    {
        NSArray *keys = [dict allKeys];
        NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            
            return [obj1 compare:obj2 options:NSNumericSearch];
        }];
        for (NSString *categoryId in sortedArray) {
            
            NSString *string = @"";
            if ( [dict[categoryId] isKindOfClass:[NSNumber class]])
            {
                string  = [NSString stringWithFormat:@"%@", dict[categoryId]];
            }
            else if ([dict[categoryId] isKindOfClass:[NSString class]])
            {
                string = dict[categoryId];
            }
            sign = [sign stringByAppendingString:string];
            
        }
    }
    
    sign = [sign stringFromMD5];
    //    resultString = [NSString stringWithFormat:@"%@%@src=iOS&ver=%@&version=%@&uuid=%@&token=%@&ts=%@",urlString,markStr,iOSVer,APP_VERSION,DEVICE_IDFA,USER_TOKEN, timeString];
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kUDtoken];
    NSString *cityId = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityid"];
    if([GW_Tool isEmptyString:cityId])
    {
        cityId = @"1";
    }
    resultString = [NSString stringWithFormat:@"%@%@version=%@&os=%@&ts=%@&sign=%@&token=%@&city=%@", urlString,markStr, APP_VERSION,@"iphone", timeString, sign, token, cityId];
    return resultString;
    
}

#pragma mark - post拼接参数
- (NSMutableDictionary *)handleParams:(NSDictionary *)params{
    
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //转为字符型
    NSString *sign = @"MhxZkhl:Xhkj-Anxin@201705";
    
    if(params)//对参数进行排序
    {
        NSArray *keys = [params allKeys];
        NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            
            return [obj1 compare:obj2 options:NSNumericSearch];
        }];
        for (NSString *categoryId in sortedArray) {
            
            NSString *string = @"";
            if ( [params[categoryId] isKindOfClass:[NSNumber class]])
            {
                string  = [NSString stringWithFormat:@"%@", params[categoryId]];
            }
            else if ([params[categoryId] isKindOfClass:[NSString class]])
            {
                string = params[categoryId];
            }
            sign = [sign stringByAppendingString:string];
            
        }
        
    }
    
    sign = [sign stringFromMD5];
    NSString *cityId = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityid"];
    if([GW_Tool isEmptyString:cityId])
    {
        cityId = @"1";
    }
    NSMutableDictionary *postValues = [@{
                                         @"version":APP_VERSION,
                                         @"os": @"iphone",
                                         //                                         @"uuid":DEVICE_IDFA,
                                         //                                         @"token":USER_TOKEN,
                                         @"ts": timeString,
                                         @"sign":sign,
                                         @"token":TOKEN,
                                         @"city" : cityId//城市 暂时是这样
                                         } mutableCopy
                                       ];
    if (params) {
        [postValues addEntriesFromDictionary:params];
    }
    return postValues;
}

@end
